/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package elaborate.h2x.transform.position;

import elaborate.h2x.transform.TransformingModel;
import elaborate.h2x.transform.TransformingNode;
import java.util.List;

/**
 * apply natural position
 * @author lendle
 */
public class NaturalTransformingNodesPositionerImpl implements TransformingNodesPositioner {

    public void determinePositions(TransformingModel model, PositionMap map) throws Exception {
        List<TransformingNode> roots=model.getRoots();
        for(TransformingNode root : roots){
            positionSubTree(model, map, null, null, root);
        }
    }

    private void positionSubTree(TransformingModel model, PositionMap positionMap, TransformingNode parentNode, TransformingNode prev, TransformingNode node) throws Exception{
        if(parentNode!=null && node.isIncludedInResult()){
            positionMap.positionNode(parentNode.getId(), (prev != null) ? prev.getId() : null, node.getId());
        }
        List<TransformingNode> childNodes = node.getChildNodes();
        //System.out.println(childNodes.size());
        prev = null;
        if (childNodes != null) {
            for (TransformingNode childNode : childNodes) {
                positionSubTree(model, positionMap, (node.isIncludedInResult())?node:parentNode, prev, childNode);
                if(childNode.isIncludedInResult()){
                    prev = childNode;
                }
            }
        }
    }
}
